<template>
    <div style="height: 100%">
        <el-container style="height: 99.8%">
            <el-aside width="200px;height: 100%">
                <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                    <el-col :span="24">
                        <span style="font-size: 20px; font-weight: 1000; color: white">
                            <el-icon><HomeFilled /></el-icon>{{ $t('组织机构') }}
                        </span>
                    </el-col>
                </el-row>
                <el-card style="height: 94%; width: 99%">
                    <channel :isreadonly="true"></channel>
                </el-card>
            </el-aside>
            <el-main style="padding: 0; overflow: hidden">
                <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                    <el-col :span="4">
                        <span style="font-size: 20px; font-weight: 1000; color: white"
                            ><el-icon><UserFilled /></el-icon>{{ $t('用户查询') }}</span
                        >
                    </el-col>
                    <el-col :span="20">
                        <div style="float: right">
                            <UiSet :type="2" :index="0" :Prop="uiSectionList" :comid="componentId" v-model:isgrant="isuigrant" @before-click="uisetbefore"></UiSet>
                        </div>
                    </el-col>
                </el-row>
                <el-card>
                    <el-form :model="findform" :inline="true" label-width="100px">
                        <el-row :gutter="10">
                            <template v-for="(item, index) in Stores.comui[componentId][0].baseProps">
                                <el-col v-if="item.visible && item.ismore == false" :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
                                    <el-form-item :label="I(item.label, item.labeleng)">
                                        <template #default>
                                            <div v-if="item.type === 'date'">
                                                <el-date-picker v-model="findform[item.prop]" type="date" clearable style="width: 160px" :id="item.prop" />
                                            </div>
                                            <div v-else-if="item.prop === 'state'">
                                                <el-select v-model="findform[item.prop]" :id="item.prop" size="default" style="width: 160px" placeholder="">
                                                    <el-option :label="$t('全部')" value="null" />
                                                    <el-option :label="$t('启用')" value="1" />
                                                    <el-option :label="$t('停用')" value="0" />
                                                </el-select>
                                            </div>
                                            <div v-else-if="item.type === 'number'">
                                                <el-input-number style="width: 160px" v-model="findform[item.prop]" :controls="false" :id="item.prop"></el-input-number>
                                            </div>
                                            <div v-else>
                                                <el-input clearable v-model="findform[item.prop]" :id="item.prop" />
                                            </div>
                                        </template>
                                    </el-form-item>
                                </el-col>
                            </template>
                            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                                <el-form-item>
                                    <el-button color="#e1d8d8" round :icon="Refresh" @click="resetForm()" id="reset">{{ $t('重置') }}</el-button>
                                    <el-button v-loading="loading" type="primary" round :icon="Search" @click="gettablelist()" id="find">{{ $t('查找') }}</el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-card>
                <el-card>
                    <el-row style="padding: 5px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                        <el-col :span="4">
                            <span style="font-size: 20px; font-weight: 1000; color: white">
                                <el-icon><Grid /></el-icon>{{ $t('列表数据') }}
                            </span>
                        </el-col>
                        <el-col :span="20">
                            <el-row justify="end" :gutter="10">
                                <el-popconfirm :title="$t('确定要删除选中的用户吗?')" :confirm-button-text="$t('是')" :cancel-button-text="$t('否')" @confirm="deleteuser()" @cancel="canceldel()">
                                    <template #reference>
                                        <el-button v-loading="loading" type="danger" :icon="Delete" round style="margin-right: 10px">{{ $t('批量删除') }}</el-button>
                                    </template>
                                </el-popconfirm>
                                <!-- <excel ref="excelRef" :index="0" :Prop="uiSectionList" :comid="componentId" :title="$t('[用户管理]')" @comfirmimput="excelimputhandle"></excel> -->
                                <el-button v-loading="loading" color="#00b794" :icon="Document" round @click="exportEvent" style="margin-left: 10px">{{ $t('Excel导出') }} </el-button>
                                <UiSet :type="1" :index="0" :Prop="uiSectionList" :comid="componentId" v-model:isgrant="isuigrant" @before-click="uisetbefore"></UiSet>
                            </el-row>
                        </el-col>
                    </el-row>
                    <!-- prettier-ignore -->
                    <vxe-table
                        :data="userdata"
                        border 
                        height="400"
                        :loading="loading" 
                        :mouse-config="{selected: true}" 
                        :row-config="{ isCurrent: true, isHover: true }" 
                        :column-config="{resizable: true}"
                        @cell-click="SetCurrent">
                         <vxe-column v-for="(column, index) in uiSectionList[0].tableProps" 
                        :field="column.prop" 
                        :title="column.label" 
                        :width="column.width"
                        :fixed="column.fixed"
                        :align="column.align">
                        <template #header>
                            <div v-if="column.type === 'checkbox'">
                                    <el-checkbox v-model="Allcheck" @change="CheckAllChange" />
                                </div>
                                <div v-else>
                                     {{ I(column.label, column.labeleng)  }}
                            </div>
                        </template>
                        <template #default="{ row,rowIndex  }">
                                <div v-if="column.type === 'checkbox'">
                                    <el-checkbox v-model="row['checked']" />
                                </div>
                                <div v-else-if="column.prop === 'state'">
                                     <el-tag v-if="row.state === 1"  effect="dark" round type="primary" >{{ $t('启用') }}</el-tag>
                                     <el-tag v-if="row.state !== 1"  effect="dark" round type="info" >{{ $t('停用') }}</el-tag>
                                </div>
                                <div v-else-if="column.type === 'action'">
                                    <el-button size="small" link @click="editdetail(rowIndex, row)">
                                    <span style="font-size: 15px; color: #07a8d9">{{ $t('编辑') }}</span>
                                    </el-button>
                                    <span style="margin: 2px">|</span>
                                    <el-popconfirm :title="$t('确定要删除选中的人员吗?')" :confirm-button-text="$t('是')" :cancel-button-text="$t('否')" @confirm="deleteuser(row['id'])" @cancel="canceldel()">
                                        <template #reference>
                                            <el-button v-loading="loading" type="danger" size="small" link style="margin-right: 10px">
                                                 <span style="font-size: 15px; color: red">{{ $t('删除') }}</span>
                                            </el-button>
                                        </template>
                                    </el-popconfirm>
                                </div>
                                <div v-else>
                                  {{ row[column.prop] }}
                                </div>
                        </template>
                        </vxe-column>
                        </vxe-table>
                        <pagemodel v-model:allcount="allcount" v-model:page="findform.page" v-model:pagecount="findform.pagecount" @pagechange="pagechange"></pagemodel>
                </el-card>
            </el-main>

            <!-- 弹窗组件 -->
            <el-dialog v-model="dialogVisible" :title="$t('修改用户')" width="750">
                <el-form :model="formdata" label-width="120" :inline="true">
                    <el-form-item :label="$t('用户编号')">
                        <el-input v-model="formdata.userid" readonly />
                    </el-form-item>
                    <el-form-item :label="$t('用户名称')">
                        <el-input v-model="formdata.name" />
                    </el-form-item>
                    <el-form-item :label="$t('工号')" style="width: 44%">
                        <empmodel v-model:name="formdata.employeenm" v-model:id="formdata.employeeid"></empmodel>
                    </el-form-item>
                    <el-form-item :label="$t('启用')">
                        <el-switch v-model="formdata.state" :active-value="1" :inactive-value="0" />
                    </el-form-item>
                    <el-form-item :label="$t('所属组织')" style="width: 44%">
                        <channelmodel v-model:name="formdata.channel" v-model:id="formdata.channelid"></channelmodel>
                    </el-form-item>
                    <el-form-item :label="$t('联系电话')">
                        <el-input v-model="formdata.tel" />
                    </el-form-item>
                    <el-form-item :label="$t('用户描述')" style="width: 92%">
                        <el-input v-model="formdata.des" type="textarea" />
                    </el-form-item>
                </el-form>
                <vxe-table :data="popTableData" border height="250" :column-config="{ resizable: true }" :mouse-config="{ selected: true }" :row-config="{ isCurrent: true, isHover: true }" @cell-click="SetCurrent">
                    <vxe-column field="roleid" :title="$t('用户描述')" width="150">
                        <template #default="{ row, rowIndex }">
                            <rolemodel v-model:name="row['rolenm']" v-model:id="row['roleid']" :isreadonly="true" @updatedata="changeroleset"></rolemodel>
                        </template>
                    </vxe-column>
                    <vxe-column field="rolenm" :title="$t('角色名称')" width="190"></vxe-column>
                    <vxe-column field="des" :title="$t('角色描述')" width="300"></vxe-column>
                    <vxe-column :title="$t('操作')" width="78">
                        <template #default="{ row, rowIndex }">
                            <el-button link @click="addrole()" type="primary">
                                <el-icon><Plus /></el-icon>
                            </el-button>
                            <span style="margin: 2px">|</span>
                            <el-button v-loading="loading" type="danger" link @click="delrole(rowIndex)">
                                <el-icon><DeleteFilled /></el-icon>
                            </el-button>
                        </template>
                    </vxe-column>
                    <template #empty>
                        <el-button link @click="addrole()" type="primary">
                            <el-icon><EditPen /></el-icon>
                            {{ $t('点击添加角色') }}
                        </el-button>
                    </template>
                </vxe-table>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogVisible = false">{{ $t('取消') }}</el-button>
                        <el-button type="primary" @click="saveuserinfo()"> {{ $t('确定') }} </el-button>
                    </div>
                </template>
            </el-dialog>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
//@ts-ignore
import { httpSend } from '@/utils/api';
import { useI18n } from 'vue-i18n';
import { getCurrentInstance, onMounted, ref, reactive, watch, onActivated, computed } from 'vue';
import { useRouter, onBeforeRouteLeave } from 'vue-router';
import type { VNode } from 'vue';
import { Setting, Refresh, Search, Document, Plus, Delete } from '@element-plus/icons-vue';
import * as XLSX from 'xlsx'; /*excel操作*/
/*组件*/
import UiSet from '@/components/share/UiSet.vue';
import excel from '@/components/share/excel.vue';
import channelmodel from '@/components/share/channelmodel.vue';
import channel from '@/components/share/channel.vue';
import rolemodel from '@/components/share/rolemodel.vue';
import empmodel from '@/components/share/empmodel.vue';
import pagemodel from '@/components/share/pagemodel.vue';
//@ts-ignore
import { TableUiSection } from '@/components/share/ui-set.interface.ts';
//@ts-ignore
import { usechannelStore, useshareStore, usegrantStore } from '@/store'; /*pina管理*/
//@ts-ignore
import { formatDate, chkgrant } from '@/globalmethods'; /*通用方法*/
const { t } = useI18n(); //多语言
const excelRef = ref(null);
//const isexcelgrant = ref(false);
const isuigrant = ref(false);
// 自定义字段配置
const componentId = 'userinfosetting';
const uiSectionList: TableUiSection[] = [
    {
        baseProps: [
            { label: '用户姓名', prop: 'name', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '用户编号', prop: 'userid', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '用户角色', prop: 'role', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '用户工号', prop: 'employeeid', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '联系电话', prop: 'tel', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '用户状态', prop: 'state', visible: true, readonly: false, type: 'select', ismore: false },
        ],
        tableProps: [
            { label: '选择', labelex: '', labeleng: '', prop: 'checked', visible: true, readonly: false, width: '80', type: 'checkbox', fixed: 'left', align: 'center' },
            { label: '用户姓名', labelex: '', labeleng: '', prop: 'name', visible: true, readonly: false, width: '140', type: 'string', fixed: null, align: 'left' },
            { label: '用户编号', labelex: '', labeleng: '', prop: 'userid', visible: true, readonly: false, width: '140', type: 'string', fixed: null, align: 'left' },
            { label: '用户状态', labelex: '', labeleng: '', prop: 'state', visible: true, readonly: false, width: '140', type: 'string', fixed: null, align: 'left' },
            { label: '用户工号', labelex: '', labeleng: '', prop: 'employeeid', visible: true, readonly: false, width: '140', type: 'string', fixed: null, align: 'left' },
            { label: '联系电话', labelex: '', labeleng: '', prop: 'tel', visible: true, readonly: false, width: '140', type: 'string', fixed: null, align: 'left' },
            { label: '所属组织', labelex: '', labeleng: '', prop: 'channel', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'center' },
            { label: '用户角色', labelex: '', labeleng: '', prop: 'rolenms', visible: true, readonly: false, width: '140', type: 'string', fixed: null, align: 'left' },
            { label: '操作', labelex: '', labeleng: '', prop: 'action', visible: true, readonly: false, width: '200', type: 'action', fixed: 'right', align: 'center' },
        ],
    },
];
const grantStore = usegrantStore() as any;
const childRef = ref(null);
const Stores = useshareStore() as any;
Stores.setcomui([componentId, uiSectionList]);
const { appContext } = getCurrentInstance();
const ElMessage = appContext.config.globalProperties.$ElMessage;
const channelStore = usechannelStore() as any;
const router = useRouter();
const loading = ref(false);
const drawer = ref(false);
const popselect = ref(0);
let userdata: any = ref([]);
const findform = reactive({
    employeeid: null,
    userid: null,
    name: null,
    tel: null,
    channel: null,
    channelid: null,
    rolenm: null,
    roleid: null,
    state: 'null',
    page: 1,
    pagecount: 10,
});
// 弹窗数据
let formdata: any = reactive({});
const popTableData = computed(() => formdata.role.filter((item) => item.isdel !== 1));
const dialogVisible = ref(false);
//动态计算表格最大高度
const tableMaxHeight = computed(() => {
    return window.innerHeight - 350;
});

let isactive = true; //处理路由缓存组件的时候，在别的路由仍然触发了当前组件监控wtach事件
// 监听部门变化
watch(
    () => channelStore.channelid,
    (newData) => {
        if (isactive && !dialogVisible.value) {
            findform.channelid = newData;
            gettablelist();
        }
    }
);
onActivated(() => {
    isactive = true;
});
onBeforeRouteLeave((to, from, next) => {
    // 在路由离开时停止watch
    isactive = false;
    next();
});

//初始化
onMounted(() => {
    //加载权限
    //isexcelgrant.value=chkgrant('用户管理', 'excelimportUsrGroup');
    isuigrant.value = chkgrant('用户管理', 'customset');
    gettablelist();
    getuiset();
});

let Allcheck = ref(false);
//表头全选/取消
const CheckAllChange = (val: boolean) => {
    userdata.value.forEach((v) => {
        v.checked = val;
    });
    userdata.value = [...userdata.value];
};
const allcount = ref(0); // 总数据条数

//获取配置数据
const getuiset = async () => {
    loading.value = true;
    let comdata = [];
    comdata[0] = componentId;
    comdata[1] = [];
    Object.assign(comdata[1], uiSectionList);
    const fd = new FormData();
    let data = { comid: componentId, userid: null };
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('getComUiSet', fd, false);
    if (res && res.code == 1) {
        if (res.data.length > 0) {
            let data = JSON.parse(res.data[0]['setjson']);
            // 如果数据依然是字符串，则需要再解析一次
            if (typeof data === 'string') {
                data = JSON.parse(data); // 第二次解析
            }
            if (data) {
                Object.assign(comdata[1], data);
            }
        }
    }
    loading.value = false;
    Stores.setcomui(comdata);
};

//页签变化
const handlePageChange = (newPage) => {
    findform.page = newPage;
    gettablelist();
};
//当前页数变化
const handleSizeChange = (val: number) => {
    findform.pagecount = val;
    gettablelist();
};
//跳转第*页回车事件
const onjumbEnter = () => {
    findform.page = jumbPage.value;
    gettablelist();
};
//查询数据
const gettablelist = async () => {
    if (!chkgrant('用户管理', 'getUserList')) {
        ElMessage.warning(t('您暂无查看权限,请联系管理员!'));
        return;
    }
    drawer.value = false;
    loading.value = true;
    const fd = new FormData();
    let data = findform;
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('getUserList', fd);
    if (res && res.code == 1) {
        userdata.value = res.data.map((v) => {
            return {
                checked: false,
                ...v,
            };
        });
        allcount.value = res.count;
    }
    loading.value = false;
};
//重置
const resetForm = () => {
    for (let key in findform) {
        if (findform.hasOwnProperty(key)) {
            if (key == 'state') {
                findform[key] = 'null';
            } else if (key == 'page') {
                findform[key] = 1;
            } else if (key == 'pagecount') {
                findform[key] = 10;
            } else {
                findform[key] = null;
            }
        }
    }
    channelStore.setform(null);
    channelStore.setid(null);
    channelStore.setname(null);
    Stores.setreset(true);
};
//编辑
const editdetail = (index, row) => {
    if (!chkgrant('用户管理', 'changeUserInfo')) {
        ElMessage.warning(t('您暂无编辑权限,请联系管理员!'));
        return;
    }
    formdata.id = userdata.value[index].id;
    formdata.userid = userdata.value[index].userid;
    formdata.name = userdata.value[index].name;
    formdata.channel = userdata.value[index].channel;
    formdata.channelid = userdata.value[index].channelid;
    formdata.state = userdata.value[index].state;
    formdata.des = userdata.value[index].des;
    formdata.tel = userdata.value[index].tel;
    formdata.employeeid = userdata.value[index].employeeid;
    formdata.employeenm = userdata.value[index].employeenm;
    formdata.role = userdata.value[index].role.map((v, index) => {
        return {
            index: index,
            ...v,
        };
    });
    dialogVisible.value = true;
};

//导出
const exportEvent = () => {
    if (!chkgrant('用户管理', 'excelout')) {
        ElMessage.warning(t('您暂无导出权限,请联系管理员!'));
        return;
    }
    const formattedData = userdata.value.map((row) => {
        // 创建一个新的对象
        const newRow = {};
        Stores.comui[componentId][0].tableProps.forEach((v) => {
            if (v.visible && v.prop != 'action' && v.prop != 'checked') {
                newRow[v.label] = !!row[v.prop] ? row[v.prop] : '';
            }
        });
        return newRow; // 返回新创建的对象
    });
    // 使用自定义标题和数据生成工作表
    const ws = XLSX.utils.json_to_sheet(formattedData); // { header }
    // 创建一个新的工作簿
    const wb = XLSX.utils.book_new();
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    // 使用文件名导出 Excel 文件
    XLSX.writeFile(wb, t('用户管理导出') + '.xlsx');
};
//接收excel子组件传过来的数据并进行处理
// const excelimputhandle = (data, iscover) => {
//     let param = {
//         iscover: iscover,
//         data: data,
//     };
//     excelimport(param);
// };
//excel导入
// const excelimport = async (data) => {
//     loading.value = true;
//     const fd = new FormData();
//     fd.append('param', JSON.stringify(data));
//     // const res = await httpSend('excelimportemployee', fd);
//     // if (res.code == 1) {
//     //     console.log('res', res);
//     //     excelRef.value?.closeform();
//     //     gettablelist();
//     // }
//     loading.value = false;
// };

//删除勾选
const deleteuser = async (id = null) => {
    if (!chkgrant('用户管理', 'deleteUserInfo')) {
        ElMessage.warning(t('您暂无删除权限,请联系管理员!'));
        return;
    }
    let idstr = null;
    if (id) {
        idstr = id;
    } else {
        idstr = userdata.value
            .filter((v) => v.checked)
            .map((item) => item.id)
            .join(',');
    }
    if (!idstr) {
        ElMessage.warning('请先选择需要删除的信息!');
        return;
    }
    loading.value = true;
    const fd = new FormData();
    fd.append('param', JSON.stringify({ id: idstr }));
    const res = await httpSend('deleteUserInfo', fd);
    if (res.code == 1) {
        gettablelist();
    }
    loading.value = false;
};
//取消删除
const canceldel = () => {
    console.log('cancel delete!');
};
//修改保存用户信息
const saveuserinfo = async () => {
    if (!chkgrant('用户管理', 'changeUserInfo')) {
        ElMessage.warning(t('您暂无保存权限,请联系管理员!'));
        return;
    }
    const fd = new FormData();
    fd.append('param', JSON.stringify(formdata));
    loading.value = true;
    try {
        const res = await httpSend('changeUserInfo', fd);
        if (res.code === 1) {
            dialogVisible.value = false;
            loadgrant();
            gettablelist();
        } else {
            console.log('失败');
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        loading.value = false;
    }
};
//新增角色
const addrole = () => {
    if (!chkgrant('用户管理', 'changeUserInfo')) {
        ElMessage.warning(t('您暂无新增权限,请联系管理员!'));
        return;
    }
    formdata.role.push({
        index: formdata.role.length,
        id: null,
        roleid: null,
        rolenm: null,
        isdel: 0,
    });
};
//删除角色
const delrole = (index) => {
    if (!chkgrant('用户管理', 'deleteUserInfo')) {
        ElMessage.warning(t('您暂无删除权限,请联系管理员!'));
        return;
    }
    if (formdata.role[index].id) {
        formdata.role[index].isdel = 1;
    } else {
        formdata.role.splice(index, 1);
    }
};

//选择表格数据
const SetCurrent = (e) => {
    popselect.value = e.row.index;
    console.log('popselect.value', popselect.value);
};

//接受角色组件传值
const changeroleset = (form: any) => {
    formdata.role[popselect.value].roleid0 = form.id;
    formdata.role[popselect.value].des = form.des;
};

//加载用户权限
const loadgrant = async () => {
    const res = await httpSend('loadgrant', {}, false);
    if (res.data) {
        grantStore.setisadmin(res.isadmin);
        grantStore.setgrantlist(res.data);
    }
};
//自定义配置权限判断
const uisetbefore = () => {
    if (!isuigrant.value) {
        ElMessage.warning(t('您暂无配置权限,请联系管理员!'));
        return;
    }
};
//页数变化重新查询
const pagechange=(e)=>{
    gettablelist();
}
const I = (label, labeleng) => {
    if (labeleng && localStorage.getItem('locale') == 'en') {
        return labeleng;
    }
    return t(label);
};
</script>

<style scope>
.el-card__body {
    padding: 5px !important;
    color: #000000;
}
</style>
